package day06;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author zouran
 * createDate：2024/7/3  18:29
 */
class AccountLock {
    private int balance;
    private boolean isActivity;

    public synchronized void put(int count) {
        while (isActivity) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        isActivity = true;
        balance += count;
        System.out.printf("%s:存入%d,当前余额%d\n", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), count, balance);
        notify();
    }

    public synchronized void get(int count) {
        while (!isActivity) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        isActivity = false;
        if (count < balance) {
            System.out.printf("%s:余额不足!,预支:%d,剩余%d\n", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), count, balance);
        } else {
            balance -= count;
            System.out.printf("%s:取出%d,当前余额%d\n", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), count, balance);
        }
        notify();
    }
}

class Daddy extends Thread {
    private AccountLock accountLock;

    Daddy(AccountLock accountLock) {
        this.accountLock = accountLock;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 5; i++) {
            accountLock.put(i * 100);
        }
    }
}

class Son extends Thread {
    private AccountLock accountLock;

    Son(AccountLock accountLock) {
        this.accountLock = accountLock;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 5; i++) {
            accountLock.get(i * 100);
        }
    }
}

public class Account {
    public static void main(String[] args) throws IOException {
        AccountLock accountLock = new AccountLock();
        Daddy daddy = new Daddy(accountLock);
        Son son = new Son(accountLock);
        daddy.start();
        son.start();
    }


}
